var houseKeeper = {};

function Display(){
	FillFilter();
	LoadHouseKeepingScreen();
}

function LoadHouseKeepingScreen(){
	componentLoading($(".tableBorder"));
	var link = "/roomService?func=ListRoomForHouseKeeping";
	simpleserviceWithError(link,null,GetHouseKeepingServiceSuccess,function(data){
		closeComponentLoading($(".tableBorder"));
	},null);
}

function GetHouseKeepingServiceSuccess(data){
	houseKeeper.data = JSON.parse(data);
	RenderHouseKeepingScreen();
}

function FilterRenderData(){
	var data = houseKeeper.data;
	var rs = [];
	if(houseKeeper.filterby != null && houseKeeper.filterby != "All")
	{
		for(var i=0;i<data.length;i++)
			if(data[i][houseKeeper.filterby] == houseKeeper.filterid)
				rs.push(data[i]);
	}
	else
		rs = [].concat(houseKeeper.data);
	SortHouseKeeperData(rs,houseKeeper);
	return rs;
}

//fill attr sortby=".." at td
//SortTable(objToKeep,callback); when render page
//SortHouseKeeperData(dataArray,objToKeep); after recieve data before fill table;
//customize SortHouseKeeperData
function SortHouseKeeperData(data,objArray){
	if(objArray.sortby == "roomName" && objArray.sortOrder == "desc") data.sort(function(a, b) {return b.roomName - a.roomName});
	else if(objArray.sortby == "roomName" && objArray.sortOrder == "asc") data.sort(function(a, b) {return a.roomName - b.roomName});
	else if(objArray.sortby == "roomtype" && objArray.sortOrder == "desc") data.sort(function(a, b) {
		var tmpa = getObjectFromSharedData(SharedData.RoomType,(a.roomtypeId));
		var tmpb = getObjectFromSharedData(SharedData.RoomType,(b.roomtypeId));
		return tmpb.shortName.localeCompare(tmpa.shortName);
	});
	else if(objArray.sortby == "roomtype" && objArray.sortOrder == "asc") data.sort(function(a, b) {
		var tmpa = getObjectFromSharedData(SharedData.RoomType,(a.roomtypeId));
		var tmpb = getObjectFromSharedData(SharedData.RoomType,(b.roomtypeId));
		return tmpa.shortName.localeCompare(tmpb.shortName);
	});
	else if(objArray.sortby == "roomstatus" && objArray.sortOrder == "desc") data.sort(function(a, b) {
		var tmpa = getObjectFromSharedData(SharedData.CleaningStatus,(a.cleaningStatusId));
		var tmpb = getObjectFromSharedData(SharedData.CleaningStatus,(b.cleaningStatusId));
		return getLocalizeCleaningStatus(tmpb.title).localeCompare(getLocalizeCleaningStatus(tmpa.title));
	});
	else if(objArray.sortby == "roomstatus" && objArray.sortOrder == "asc") data.sort(function(a, b) {
		var tmpa = getObjectFromSharedData(SharedData.CleaningStatus,(a.cleaningStatusId));
		var tmpb = getObjectFromSharedData(SharedData.CleaningStatus,(b.cleaningStatusId));
		return getLocalizeCleaningStatus(tmpa.title).localeCompare(getLocalizeCleaningStatus(tmpb.title));
	});
	else if(objArray.sortby == "reststatus" && objArray.sortOrder == "desc") data.sort(function(a, b) {
		var tmpa = getObjectFromSharedData(SharedData.ResvStatus,(a.status));
		var tmpb = getObjectFromSharedData(SharedData.ResvStatus,(b.status));
		return getLocalizeResvStatus((tmpb==null)?null:tmpb.title).localeCompare(getLocalizeResvStatus((tmpa==null)?null:tmpa.title));
	});
	else if(objArray.sortby == "reststatus" && objArray.sortOrder == "asc") data.sort(function(a, b) {
		var tmpa = getObjectFromSharedData(SharedData.ResvStatus,(a.status));
		var tmpb = getObjectFromSharedData(SharedData.ResvStatus,(b.status));
		return getLocalizeResvStatus((tmpa==null)?null:tmpa.title).localeCompare(getLocalizeResvStatus((tmpb==null)?null:tmpb.title));
	});
	else if(objArray.sortby == "housekeeper" && objArray.sortOrder == "desc") data.sort(function(a, b) {
		var tmpa = GetStaffName(getObjectFromSharedData(houseKeeper.HouseKeeper,(a.staff)));
		var tmpb = GetStaffName(getObjectFromSharedData(houseKeeper.HouseKeeper,(b.staff)));
		return ((tmpb==null)?label_NotAssigned:tmpb).localeCompare((tmpa==null)?label_NotAssigned:tmpa);
	});
	else if(objArray.sortby == "housekeeper" && objArray.sortOrder == "asc") data.sort(function(a, b) {
		var tmpa = GetStaffName(getObjectFromSharedData(houseKeeper.HouseKeeper,(a.staff)));
		var tmpb = GetStaffName(getObjectFromSharedData(houseKeeper.HouseKeeper,(b.staff)));
		return ((tmpa==null)?label_NotAssigned:tmpa).localeCompare((tmpb==null)?label_NotAssigned:tmpb);
	});
	
	return data;
}
function GetStaffName(s){
	if(s==null)return s;
	var name = "";
	if(s.firstName!=null) name = s.firstName;
	if(s.lastName!=null) name = name + " " + s.lastName;
	return name;
}
function SortTable(objData,callback){
	$("[sortby]").click(function(e){
		if(objData.sortby != $(this).attr("sortby"))
		{
			objData.sortby = $(this).attr("sortby");
			objData.sortOrder = "desc";
		}
		else{
			if(objData.sortOrder == "desc") objData.sortOrder = "asc";
			else if(objData.sortOrder == "asc"){
				delete objData.sortby;
				delete objData.sortOrder;
			}
		}
		FillSortIcon($("[sortby]"),objData);
		if(callback!=null) callback();
	});
}
function FillSortIcon(doms,objData){
	doms.each(function(e){$(this).find("span").remove()});
	if(objData.sortby == null) return;
	var icon = (objData.sortOrder=="desc")?"▼":"▲";
	var dom = doms.parent().find("[sortby="+objData.sortby+"]");
	dom.append("<span>"+icon+"</span>");
}

function isCheckInOrCheckOut(status){
	if(status == -1) return false;
	var rs = getObjectFromSharedData(SharedData.ResvStatus,status);
	if(rs!=null && (rs.title == "Checked-in Rooms" || rs.title == "Checked-out Rooms"))
		return true;
	return false;
}

function RenderStat(){
	var checkinToday = 0;
	var checkoutToday = 0;
	var occToday = 0;
	var avaliable = 0;
	var checkedout = 0;
	
	var touchup = 0;
	var dirty = 0;
	var inspect = 0;
	var clean = 0;
	var repair = 0;
	for(var i=0;i<houseKeeper.data.length;i++){
		if(houseKeeper.data[i].statusC == "checkIn")checkinToday++;
		else if(houseKeeper.data[i].statusC == "checkout")checkoutToday++;
		else if(houseKeeper.data[i].statusC == "occupied")occToday++;
		else if(houseKeeper.data[i].statusC == "checkout"){
			var s = getObjectFromSharedData(SharedData.ResvStatus,houseKeeper.data[i].status);
			if(s.title == "Checked-out Rooms") checkedout++;
		}
		if(houseKeeper.data[i].status == "-1")avaliable++;
		var cleaning = getObjectFromDataIndex(SharedData.CleaningStatus,"id",houseKeeper.data[i].cleaningStatusId);
		if(cleaning.title=="Touch-Up Rooms")touchup++;
		else if(cleaning.title=="Dirty Rooms")dirty++;
		else if(cleaning.title=="Inspect Rooms")inspect++;
		else if(cleaning.title=="Clean Rooms")clean++;
		else if(cleaning.title=="Repair Rooms")repair++;
	}	
	$(".housekeepingtable [name=todaycheckin]").html(checkinToday);
	$(".housekeepingtable [name=todaycheckout]").html(checkoutToday);
	$(".housekeepingtable [name=avaliable]").html(avaliable);
	$(".housekeepingtable [name=occ]").html(occToday);
	$(".housekeepingtable [name=checkedOut]").html(checkedout);
	
	$(".housekeepingtable [name=totalCleanwaiting]").html(dirty);
	$(".housekeepingtable [name=totalTouchUp]").html(touchup);
	$(".housekeepingtable [name=totalClean]").html(clean);
	$(".housekeepingtable [name=totalRepair]").html(repair);
	$(".housekeepingtable [name=totalInspect]").html(inspect);
}

function RenderHouseKeepingScreen(){
	closeComponentLoading($(".tableBorder"));
	$(".housekeepertable tr").not(":first").remove();
	
	//filter
	var data = FilterRenderData();
	$(".tableBorder input[type=checkbox][name=All]").removeAttr("checked");
	for(i=0;i<data.length;i++)
	{
		var clss = (i%2==0)? "odd":"even";
		var cleaning = getObjectFromDataIndex(SharedData.CleaningStatus,"id",data[i].cleaningStatusId);
		var status = data[i].status;
		var notAssign = (status=="-1");
		var yesterdayNotAssign = !isCheckInOrCheckOut(data[i].yesterday);
		var s = getObjectFromSharedData(SharedData.ResvStatus,status);
		var staff = data[i].staff;
		var styleNotAssign = (staff == "")?"text-align:center;" : "";
		var name = "";
		if(staff != ""){
			var st = getObjectFromSharedData(houseKeeper.HouseKeeper,staff);
			if(st.firstName!=null) name = st.firstName;
			if(st.lastName!=null) name = name + " " + st.lastName;
		}
		var resvColor = (notAssign)? "#fff" : s.color;
		var closeElm = "";
		var nm = " name='staffnm'";
		if(staff!=""){
			nm += " refid='"+staff+"'";
			closeElm = "<img src='/images/HouseKeeping/close.png'/ style='float:right;' onclick='removeHouseKeeper($(this));'>";
		}
		var stringFormat = "<tr class="+clss+" roomid='{0}'>" +
				"<td class='center'>{1}</td>" +
				"<td class='center'>{2}</td>" +
				"<td>{3}</td>" +
				"<td name='clstatus' class='link' style='color:#000;background-color:{4};padding:0 6px;'>{5}</td>" +
				"<td style='background-color:"+resvColor+"'>{6}</td>" +
				"<td name='ref' class='link' style='color:#000;padding:0 6px;'>{7}</td>" +
				"<td class='link' style='color:#000;"+styleNotAssign+"'"+nm+">{8}"+closeElm+"</td>" +
			"</tr>";
		$(".housekeepertable").append(stringFormat.format(
			data[i].id,
			"<input type='checkbox'>",
			data[i].roomName,
			getObjectFromDataIndex(SharedData.RoomType,"id",data[i].roomtypeId).shortName,
			cleaning.color,
			'<span refid="'+cleaning.id+'" style="padding:0 6px;">'+getLocalizeCleaningStatus(cleaning.title)+'</span>',
			(notAssign)? todayroomstatus_empty : getLocalizeResvStatus(s.title),
			'<span style="padding:0 6px;">'+data[i].preference+'</span>',
			(staff == "")? label_selectEmployee: name
		));
	}
	RenderStat();
	FillHouseKeepingEvent();
}

function removeHouseKeeper(dom){
	dom.parents("td:first").removeAttr("name");
	dom.parents("td:first").removeAttr("refid");
	var roomId = dom.parents("tr:first").attr("roomid");
	var userId=-1
	componentLoading($(".tableBorder"));
	simpleserviceWithError("/houseKeepingService",{func:"UpdateHouseKeeping",roomId:roomId,userId:userId},
	function(data,obj){
		closeComponentLoading($(".tableBorder"));
		var objArray = JSON.parse(data);
		var room = getObjectFromSharedData(houseKeeper.data,objArray.roomId);
		room.preference = objArray.reference;
		room.staff = objArray.staffString;
		RenderHouseKeepingScreen();
	},
	function(data,obj){
		closeComponentLoading($(".tableBorder"));
	},null);
}

function FillHouseKeepingEvent(){
	checkedHouseKeepingElement();
	changeclstatus();
	EditRef();
	EditStaff();
}

function EditStaff(){
	$("td[name=staffnm]").click(function(e){
		var el = $(e.srcElement);
		if(el[0].tagName == "IMG") return;
		var content = $("<select><option value='-1'>"+label_NotAssigned+"</option></select>");
		for(i=0;i<houseKeeper.HouseKeeper.length;i++)
		{
			var name = "";
			if(houseKeeper.HouseKeeper[i].firstName!=null) name = houseKeeper.HouseKeeper[i].firstName;
			if(houseKeeper.HouseKeeper[i].lastName!=null) name = name + " " + houseKeeper.HouseKeeper[i].lastName;
			var option = optionString.format(houseKeeper.HouseKeeper[i].id,name);
			if(el.attr("refid") == houseKeeper.HouseKeeper[i].id)
				content.append($(option).attr("selected","true"));
			else
				content.append(option);
		}
		var str = content.wrap('<div></div>').parent().html();
		var dialog = housekeepingconfirmdialog(this,str,function(obj){
			var roomId = $(obj.args).parents("tr:first").attr("roomid");
			var userId = obj.dialog.find("option:selected").val();
			componentLoading($(".tableBorder"));
			simpleserviceWithError("/houseKeepingService",{func:"UpdateHouseKeeping",roomId:roomId,userId:userId},
			function(data,obj){
				closeComponentLoading($(".tableBorder"));
				var objArray = JSON.parse(data);
				var checkLogOut = checkSessionAdmin(objArray);
				if(checkLogOut)
					return;
				var room = getObjectFromSharedData(houseKeeper.data,objArray.roomId);
				room.preference = objArray.reference;
				room.staff = objArray.staffString;
				RenderHouseKeepingScreen();
			},
			function(data,obj){
				closeComponentLoading($(".tableBorder"));
			},obj);
		});
		dialog.parent().css({width:"auto"});
	});
}

function EditRef(){
	$("td[name=ref]").click(function(){
		var dom = $(this).find("span");
		fillSimpleTextEdit(dom,false,function(obj){
			var ref = obj.textbox.val();
			var roomId = obj.dom.parents("tr:first").attr("roomId");
			componentLoading($(".tableBorder"));
			simpleserviceWithError("/houseKeepingService",{func:"UpdateHouseKeeping",roomId:roomId,ref:ref},
			function(data,obj){
				closeComponentLoading($(".tableBorder"));
				var objArray = JSON.parse(data);
				var checkLogOut = checkSessionAdmin(objArray);
				if(checkLogOut)
					return;
				var room = getObjectFromSharedData(houseKeeper.data,objArray.roomId);
				room.preference = objArray.reference;
				room.staff = objArray.staffString;
				RenderHouseKeepingScreen();
			},
			function(data,obj){
				closeComponentLoading($(".tableBorder"));
			},obj);
		})
	});
}

function checkedHouseKeepingElement()
{
	$(".tableBorder input[type=checkbox]").change(function(e){
		if($(e.srcElement).attr("name")!="All")
		{
			var l = $(".tableBorder input[type=checkbox]").not($("[name=All]")).not(":checked").length;
			$(".tableBorder input[type=checkbox][name=All]").attr("checked",(l == 0));
		}
		else
			$(".tableBorder input[type=checkbox]").not($(e.srcElement)).attr("checked",$(e.srcElement).is(":checked"));
	});
}

function changeclstatus(){
	$("[name=clstatus]").mouseenter(function() {
		var hexString = toHexColor($(this).css("background-color"));
		$(this).attr("leavecolor",hexString);
		$(this).css("background-color",LightenDarkenColor(hexString,20));
	});
	$("[name=clstatus]").mouseleave(function(){
		
		var hexString = $(this).attr("leavecolor");
		if(hexString!=null && hexString!=""){
			$(this).css("background-color",hexString);
		}
		$(this).removeAttr("leavecolor");
	});
//	$("[name=clstatus]").click(function(e){
//		var el = $(e.srcElement);
//		if(!$(e.srcElement).is("span"))
//			el = el.find("span");
//		
//		var data = [];
//		for(i=0;i<SharedData.CleaningStatus.length;i++)
//		{
//			if(SharedData.CleaningStatus[i].title == "DNR") continue;
//			var tmp = {};
//			tmp.title = getLocalizeCleaningStatus(SharedData.CleaningStatus[i].title);
//			tmp.id = SharedData.CleaningStatus[i].id;
//			data.push(tmp);
//		}
//		fillSimpleDropdown(el,data,"id","title",function(obj){
//			var roomId = obj.dom.parents("tr:first").attr("roomid");
//			var status = obj.select.find(":selected").val();
//			componentLoading($(".tableBorder"));
//			simpleserviceWithArgs("/roomService",{func:"changCleaningStatus",roomId:roomId,cleanStatus:status},function(data,args){
//				var objArray = JSON.parse(data);
//				var cleaning = getObjectFromSharedData(houseKeeper.data,objArray.id);
//				cleaning.cleaningStatusId = objArray.cleaningStatusString;
//				RenderHouseKeepingScreen();
//			},obj);
//		})
//	});
	$("[name=clstatus]").click(function(e){
		var el = $(e.srcElement);
		if(!$(e.srcElement).is("span"))
			el = el.find("span");
		var content = $("<select></select>");
		for(i=0;i<SharedData.CleaningStatus.length;i++)
		{
			if(SharedData.CleaningStatus[i].title == "DNR") continue;
			var tmp = {};
			tmp.title = getLocalizeCleaningStatus(SharedData.CleaningStatus[i].title);
			tmp.id = SharedData.CleaningStatus[i].id;
			var option = optionString.format(tmp.id,tmp.title);
			if(el.attr("refid") == SharedData.CleaningStatus[i].id)
				content.append($(option).attr("selected","true"));
			else
				content.append(option);
		}
		var str = content.wrap('<div></div>').parent().html();
		var dialog = housekeepingconfirmdialog(this,str,function(obj){
			var roomId = $(obj.args).parents("tr:first").attr("roomid");
			var status = obj.dialog.find("option:selected").val();
			componentLoading($(".tableBorder"));
			simpleserviceWithArgs("/roomService",{func:"changCleaningStatus",roomId:roomId,cleanStatus:status},function(data,args){
				var objArray = JSON.parse(data);
				var checkLogOut = checkSessionAdmin(objArray);
				if(checkLogOut)
					return;
				var cleaning = getObjectFromSharedData(houseKeeper.data,objArray.id);
				cleaning.cleaningStatusId = objArray.cleaningStatusString;
				RenderHouseKeepingScreen();
			});
		});
		//dialog.find("select").easyDropDown();
		dialog.parent().css({width:"auto"});
	});
}

function getLocalizeTodayResvRoomStatus(resvStatus){
	if(resvStatus=="CheckinToday"){
		return todayroomstatus_todaycheckin;
	}else if(resvStatus=="CheckedOut"){
		return todayroomstatus_checkedOut;
	}else if(resvStatus=="CheckoutToday"){
		return todayroomstatus_todaycheckout;
	}else if(resvStatus=="StayToday"){
		return todayroomstatus_stay;
	}else{
		return todayroomstatus_empty;
	}
}

function housekeepingconfirmdialog(caller,content,callback){
	var buttons = [
		{ title:"Cancel",style:"float:center;", callback: function(thisdialog,args){
			thisdialog.dialog("close");
		}},
		{ title:"Save",style:"float:center;", callback: function(thisdialog,args){
			thisdialog.dialog("close");
			var rs={dialog:thisdialog,args:args};
			if(callback!=null)callback(rs);
		}}
	];
	var dialog = housekeepingdialog(caller,content,buttons,caller);
	dialog.css("overflow","hidden");
	dialog.parent().css({left:$(caller).position().left,top:$(caller).position().top})
	return dialog;
}

function housekeepingdialog(caller,content,arrayButton,args)
{
	if($("#loadingScreen").is(":visible")) closeWaitingDialog();
	var msgDialog = $("#BlankDialog").clone();
	msgDialog.dialog({
		resizable : false,
		modal: false,
		clickOutside: true,
		clickOutsideTrigger: caller,
		close: function() { msgDialog.dialog('destroy').remove(); },
	});
	var maxZ = MaxDivZIndex();
	msgDialog.parent().find('.ui-dialog-titlebar').css("display","none");
	msgDialog.parent().css("z-index",maxZ+2);
	msgDialog.parent().next().css("z-index",maxZ+1);
	
	//msgDialog.parent().find('')
	msgDialog.css("padding",0);
	msgDialog.css("margin",0);
	msgDialog.html('<div class="ui-newdialog-content">'+content+'</div>' +
		'<div class="ui-newdialog-button"><div style="text-align:center;"></div></div>');
	msgDialog.css("min-height","")
	
	if(arrayButton != null)
	for(var i=arrayButton.length-1;i>=0;i--)
	{
		var style = "float:right";
		if(arrayButton[i].style != null) style = arrayButton[i].style;
		var btn = $('<button style="'+style+'" class="btn-small">' + arrayButton[i].title + '</button>');
		btn.bind('click', arrayButton[i], function(event) {
			event.data.callback(msgDialog,args);
		});
		msgDialog.find(".ui-newdialog-button div").append(btn);
	}
	
	return msgDialog;
}
$(function(){$.widget("ui.dialog",$.ui.dialog,{options:{clickOutside:false,clickOutsideTrigger:""},open:function(){var e=$(this.options.clickOutsideTrigger);var t=this;if(this.options.clickOutside){$(document).on("click.ui.dialogClickOutside"+t.eventNamespace,function(n){if($(n.target).css("display")!="none"&&$(n.target).attr("from")!='simpledialog'&&$(n.target).closest($(e)).length==0&&$(n.target).closest($(t.uiDialog)).length==0){t.close()}})}this._super()},close:function(){var e=this;$(document).off("click.ui.dialogClickOutside"+e.eventNamespace);this._super()}})})

function printHouse(){
	$.getScriptIfNotExist("/js/housekeeping/printHouseKeeping.js").done(function(script,textStatus)
	{
		//filter
		var printDataHouse = "";
		var data = FilterRenderData();
		for(i=0;i<data.length;i++)
		{
			var clss = (i%2==0)? "odd":"even";
			var cleaning = getObjectFromDataIndex(SharedData.CleaningStatus,"id",data[i].cleaningStatusId);
			var status = data[i].status;
			var notAssign = (status=="-1");
			var yesterdayNotAssign = !isCheckInOrCheckOut(data[i].yesterday);
			var s = getObjectFromSharedData(SharedData.ResvStatus,status);
			var staff = data[i].staff;
			var styleNotAssign = (staff == "")?"text-align:center;" : "";
			var name = "";
			if(staff != ""){
				var st = getObjectFromSharedData(houseKeeper.HouseKeeper,staff);
				if(st.firstName!=null) name = st.firstName;
				if(st.lastName!=null) name = name + " " + st.lastName;
			}
			var resvColor = (notAssign)? "#fff" : s.color;
			var closeElm = "";
			var nm = " name='staffnm'";
			if(staff!=""){
				nm += " refid='"+staff+"'";
				closeElm = "<img src='/images/HouseKeeping/close.png'/ style='float:right;' onclick='removeHouseKeeper($(this));'>";
			}
			var stringFormat = "<tr class="+clss+" roomid='{0}'>" +
					"<td class='center'>{1}</td>" +
					"<td>{2}</td>" +
					"<td name='clstatus' class='link' style='color:#000;background-color:{3};padding:0 6px;'>{4}</td>" +
					"<td style='background-color:"+resvColor+"'>{5}</td>" +
					"<td name='ref' class='link' style='color:#000;padding:0 6px;'>{6}</td>" +
					"<td class='link' style='color:#000;"+styleNotAssign+"'"+nm+">{7}"+closeElm+"</td>" +
				"</tr>";
			printDataHouse += (stringFormat.format(
					data[i].id,
					data[i].roomName,
					getObjectFromDataIndex(SharedData.RoomType,"id",data[i].roomtypeId).shortName,
					cleaning.color,
					'<span refid="'+cleaning.id+'" style="padding:0 6px;">'+getLocalizeCleaningStatus(cleaning.title)+'</span>',
					(notAssign)? todayroomstatus_empty : getLocalizeResvStatus(s.title),
					'<span style="padding:0 6px;">'+data[i].preference+'</span>',
					(staff == "")? label_selectEmployee: name
				));
		}
		var filter = $("[name=filterby] option:selected").text();
		printHuseKeep(printDataHouse,filter);
	});
}